package com.atguigu.syt.cmn.service.impl;

import com.atguigu.syt.cmn.mapper.DictMapper;
import com.atguigu.syt.cmn.service.DictService;
import com.atguigu.syt.cmn.service.DictTypeService;
import com.atguigu.syt.model.cmn.Dict;
import com.atguigu.syt.model.cmn.DictType;
import com.atguigu.syt.vo.cmn.DictTypeVo;
import com.atguigu.syt.vo.cmn.DictVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2023-05-24
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    private DictTypeService dictTypeService;

    //获取数据字典嵌套列表
    @Override
    public List<DictTypeVo> findAllDictList() {
        List<DictTypeVo> dictTypeVoList = new ArrayList<>();
        //1查询所有字典类型数据 List<DictType>
        List<DictType> dictTypeList = dictTypeService.list();
        //2查询所有字典数据 List<Dict>
        List<Dict> dictList = this.list();
        //3遍历字典类型集合List<DictType>
        dictTypeList.forEach(dictType -> {
            //4封装字典类型数据DictTypeVo
            DictTypeVo dictTypeVo = new DictTypeVo();
            dictTypeVo.setName(dictType.getName());
            dictTypeVo.setId("parent-"+dictType.getId());
            //5筛选跟当前DictType匹配的List<Dict>
            List<Dict> subDictList = dictList.stream().filter(dict ->
                    dict.getDictTypeId().longValue() == dictType.getId().longValue()
            ).collect(Collectors.toList());
            //6封装子数据集合List<DictVo>
            List<DictVo> children = new ArrayList<>();
            subDictList.forEach(dict -> {
                DictVo dictVo = new DictVo();
                dictVo.setId("children-" +dict.getId());
                dictVo.setName(dict.getName());
                dictVo.setValue(dict.getValue());
                children.add(dictVo);
            });
            //7把List<DictVo>存入DictTypeVo
            dictTypeVo.setChildren(children);
            //8把DictTypeVo存入List<DictTypeVo>
            dictTypeVoList.add(dictTypeVo);
        });
        return dictTypeVoList;
    }

    /**
     * 根据数据字典类别和字典值获取字典名称
     * @param dictTypeId
     * @param value
     * @return
     */
    @Override
    public String getNameByDictTypeIdAndValue(Long dictTypeId, String value) {
        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getDictTypeId,dictTypeId);
        queryWrapper.eq(Dict::getValue,value);
        Dict dict = baseMapper.selectOne(queryWrapper);
        if (dict != null){
            return dict.getName();
        }
        return " ";
    }
}
